package com.qsl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.qsl.entity.TblClassStudent;
import com.qsl.mapper.TblClassStudentMapper;
import com.qsl.service.TblClassStudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description: xxx描述
 * @author: 博客园@青石路
 * @date: 2023/7/30 10:33
 */
@Service
public class TblClassStudentServiceImpl extends ServiceImpl<TblClassStudentMapper, TblClassStudent> implements TblClassStudentService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveOrUpdate(List<TblClassStudent> classStudents) {
        if(CollectionUtils.isEmpty(classStudents)) {
            return;
        }
        // 排序处理，保证不同线程申请锁的顺序是一致的
        Collections.sort(classStudents, Comparator.comparing(TblClassStudent::getId));
        classStudents.forEach(classStudent -> {
            this.getBaseMapper().saveOrUpdate(classStudent);
            try {
                // 为了复现问题
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveOrUpdatePlus(List<TblClassStudent> classStudents) {
        if(CollectionUtils.isEmpty(classStudents)) {
            return;
        }
        // 排序处理，保证不同线程申请锁的顺序是一致的
        Collections.sort(classStudents, Comparator.comparing(TblClassStudent::getId));
        // 批量更新不是全量一次更新，mysql对sql长度有限制
        // 利用 guava 工具方法进行分批，每一批大小，大家视情况而定
        List<List<TblClassStudent>> partitions = Lists.partition(classStudents, 500);
        partitions.forEach(partition -> this.baseMapper.batchSaveOrUpdate(partition));
    }
}
